import { createStore } from 'vuex'
import TravelAPI from '../api/travel'

// 安全操作localStorage（仅在浏览器环境中）
const safeLocalStorage = {
  getItem: (key, defaultValue = null) => {
    if (typeof window !== 'undefined' && window.localStorage) {
      return localStorage.getItem(key) || defaultValue
    }
    return defaultValue
  },
  setItem: (key, value) => {
    if (typeof window !== 'undefined' && window.localStorage) {
      localStorage.setItem(key, value)
    }
  },
  removeItem: (key) => {
    if (typeof window !== 'undefined' && window.localStorage) {
      localStorage.removeItem(key)
    }
  }
}

export default createStore({
  state: {
    user: null,
    token: safeLocalStorage.getItem('token'),
    isAuthenticated: !!safeLocalStorage.getItem('token'),
    attractions: [],
    currentRoute: null,
    budget: 1000,
    currentRole: safeLocalStorage.getItem('currentRole', 'guest')
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_ROLE(state, role) {
      state.currentRole = role
      safeLocalStorage.setItem('currentRole', role)
    },
    SET_TOKEN(state, token) {
      state.token = token
      state.isAuthenticated = !!token
      if (token) {
        safeLocalStorage.setItem('token', token)
      } else {
        safeLocalStorage.removeItem('token')
      }
    },
    SET_ATTRACTIONS(state, attractions) {
      state.attractions = attractions
    },
    SET_CURRENT_ROUTE(state, route) {
      state.currentRoute = route
    },
    SET_BUDGET(state, budget) {
      state.budget = budget
    },
    LOGOUT(state) {
      state.user = null
      state.token = null
      state.isAuthenticated = false
      state.currentRole = 'guest'
      safeLocalStorage.removeItem('token')
      safeLocalStorage.removeItem('currentRole')
    }
  },
  actions: {
    async login({ commit }, { username, password }) {
      try {
        const response = await TravelAPI.login({ username, password })
        // 确保token和user都正确设置
        if (response.token) {
          commit('SET_TOKEN', response.token)
        }
        if (response.user) {
          commit('SET_USER', response.user)
        }
        return { success: true, token: response.token, user: response.user }
      } catch (error) {
        console.error('登录错误详情:', error)
        let errorMessage = '登录失败'
        if (error.response) {
          if (error.response.data) {
            if (typeof error.response.data === 'string') {
              errorMessage = error.response.data
            } else if (error.response.data.error) {
              errorMessage = error.response.data.error
            } else if (error.response.data.detail) {
              errorMessage = error.response.data.detail
            }
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        return { success: false, error: errorMessage }
      }
    },
    async register(context, userData) {
      try {
        console.log('开始注册，发送数据:', { ...userData, password: '***', password_confirm: '***' })
        const response = await TravelAPI.register(userData)
        console.log('注册成功，响应数据:', response)
        
        // 注册成功后不自动登录，只返回成功状态和用户基本信息
        // 不设置token和user到store，需要用户手动登录
        return { 
          success: true, 
          message: response?.message || '注册成功',
          user: response?.user 
        }
      } catch (error) {
        console.error('注册错误详情:', error)
        console.error('错误响应:', error.response)
        console.error('错误响应数据:', error.response?.data)
        console.error('错误状态码:', error.response?.status)
        
        // 处理不同的错误格式
        let errorMessage = '注册失败'
        let errorDetails = null
        
        if (error.response) {
          const responseData = error.response.data
          
          if (responseData) {
            // 处理字符串错误
            if (typeof responseData === 'string') {
              errorMessage = responseData
            }
            // 处理对象错误
            else if (typeof responseData === 'object') {
              // 优先使用error字段
              if (responseData.error) {
                errorMessage = responseData.error
              }
              // 使用details字段（包含字段验证错误）
              if (responseData.details) {
                errorDetails = responseData.details
                // 将details对象转换为可读的错误信息
                const detailMessages = []
                Object.keys(responseData.details).forEach(key => {
                  const fieldErrors = Array.isArray(responseData.details[key]) 
                    ? responseData.details[key] 
                    : [responseData.details[key]]
                  detailMessages.push(`${key}: ${fieldErrors.join(', ')}`)
                })
                if (detailMessages.length > 0) {
                  errorMessage = detailMessages.join('; ')
                }
              }
              // 直接是字段错误对象（DRF的ValidationError格式）
              else if (!responseData.error && !responseData.detail) {
                errorDetails = responseData
                const fieldErrors = []
                Object.keys(responseData).forEach(key => {
                  const fieldError = Array.isArray(responseData[key]) 
                    ? responseData[key] 
                    : [responseData[key]]
                  fieldErrors.push(`${key}: ${fieldError.join(', ')}`)
                })
                if (fieldErrors.length > 0) {
                  errorMessage = fieldErrors.join('; ')
                }
              }
              // 使用detail字段
              else if (responseData.detail) {
                errorMessage = responseData.detail
              }
            }
          }
          
          // 根据状态码设置默认错误信息
          if (error.response.status === 400 && !errorDetails) {
            errorMessage = '请求参数错误，请检查输入信息'
          } else if (error.response.status === 500) {
            errorMessage = '服务器错误，请稍后重试'
          } else if (error.response.status === 0 || !error.response.status) {
            errorMessage = '网络错误，请检查后端服务是否运行'
          }
        } else if (error.message) {
          errorMessage = error.message
          if (error.message.includes('Network Error') || error.message.includes('timeout')) {
            errorMessage = '网络连接失败，请检查后端服务是否运行'
          }
        }
        
        return { 
          success: false, 
          error: errorMessage,
          details: errorDetails
        }
      }
    },
    async fetchUserInfo({ commit, state }) {
      if (!state.token) return
      try {
        const response = await TravelAPI.getCurrentUser()
        commit('SET_USER', response)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        commit('LOGOUT')
      }
    },
    logout({ commit }) {
      commit('LOGOUT')
    },
    async fetchAttractions({ commit }) {
      try {
        const response = await TravelAPI.getAttractions()
        commit('SET_ATTRACTIONS', response.results || response)
      } catch (error) {
        console.error('获取景点列表失败:', error)
      }
    }
  },
  getters: {
    isAuthenticated: state => state.isAuthenticated,
    currentUser: state => state.user,
    token: state => state.token,
    isAdmin: state => {
      // 判断用户是否为管理员
      return state.user?.is_staff || state.user?.is_superuser || state.user?.is_admin || false
    }
  },
  modules: {}
})
